package com.pandaroid.pandaclockv1;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;

/**
 * AppWidget Configuration Activity
 * 
 * com.pandaroid.clockno1
 * PandaClockConfigureActivity.java
 *
 * @author junhwan_kim
 * @date 2011. 4. 29. 오전 10:59:49
 * @Version 
 */ 
public class PandaClockConfigure extends Activity {
	
	private static final String TAG = "PandaClockV1";
	
	public static final String THEME_1 = "Theme_1";
	public static final String THEME_2 = "Theme_2";
	public static final String THEME_3 = "Theme_3";
	
	private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	private String selectedTheme;
	private boolean[] downlaodedTheme = {false};
	
	/**
	 * Widget Id 추출 
	 * Image Directory를 Spinner에 List
	 * Setting On/Off Item을 ListView에 List
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 * @Method onCreate
	 * @param savedInstanceState
	 *
	 * @author junhwan_kim
	 * @date 2011. 4. 29. 오전 10:59:32
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    Log.i(TAG, "DateWidgetConfigureActivity-onCreate()");
		
	    /// 기본 선택값을 CANCELED로 지정해 사용자가 뒤로가기로 Activity를 닫는 경우 취소 결과값을 반환하도록 함.
	    setResult(RESULT_CANCELED);
	    
	    setContentView(R.layout.appwidget_configure);
	    
	    /// 추가하려는 widgetID 추출
	    Intent intent = getIntent();
	    mAppWidgetId = intent.getIntExtra("SELECTED_WIDGET_ID", AppWidgetManager.INVALID_APPWIDGET_ID);
	    
	    /// 정상적인 경로로 호출되지 않은 경우 Activity를 종료한다.
	    if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
	    	mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
	    	if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
	    		finish();
	    	} else {
	    		String [] initPrefValue = {String.valueOf(mAppWidgetId), THEME_1, "1", "1", "1"};
		    	PandaClockPreferences.setPref(getBaseContext(), initPrefValue);
	    	}
	    }
	    
	    /// Shared Preferences에서 설정값을 가져온다., junhwan_kim, 2011.05.12
	    String[] prefValue = PandaClockPreferences.getPref(this, mAppWidgetId);
	    selectedTheme = prefValue[PandaClockPreferences.THEME];
	    
	    // start coverflow
	    BitmapDrawable drawable1 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_1);
	    BitmapDrawable drawable2 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_2);
	    BitmapDrawable drawable3 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_next);
	    BitmapDrawable drawable4 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_1_checked);
	    BitmapDrawable drawable5 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_2_checked);
	    BitmapDrawable drawable6 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_3_checked);
	    
	    BitmapDrawable[] images = {
	    		drawable1,
	    		drawable2,
	    		drawable3
	    };
	    
	    // 다른 패키지에서 리소스 참조하기
        Context con1;
		try {
			con1 = createPackageContext("com.myjjun.pandaclocktheme1", 0);
			Resources res1 = con1.getResources(); 
	        int id = res1.getIdentifier("theme_1", "drawable", "com.myjjun.pandaclocktheme1");
	        BitmapDrawable bd = (BitmapDrawable)res1.getDrawable(id);
	        images[2] = bd;
	        downlaodedTheme[0] = true;	// 테마를 다운 받았음.
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// 선택한 테마 체크한 이미지로 변경
		if (selectedTheme.equals(THEME_1)) {
			images[0] = drawable4;
		} else if (selectedTheme.equals(THEME_2)) {
			images[1] = drawable5;
		} else if (selectedTheme.equals(THEME_3) && downlaodedTheme[0] == true) {
			images[2] = drawable6;
		}
		
		// 이미지를 Adapter로 연결
		ImageAdapter adapter = new ImageAdapter(this, images);
		adapter.createReflectedImages();
		
		GalleryFlow galleryFlow = (GalleryFlow) findViewById(R.id.Gallery01);
		galleryFlow.setAdapter(adapter);
		galleryFlow.setOnItemClickListener(mItemClickListener);
		// end coverflow
		
	    // Splash(로딩화면) 띄우기
	    startActivity(new Intent(this, SplashActivity.class));
	    
	    // set Listener
    	findViewById(R.id.btnOK).setOnClickListener(mClickListener);
	    findViewById(R.id.btnCancel).setOnClickListener(mClickListener);
	}
	
	/**
	 * GalleryFlow 선택시 이벤트
	 */
	AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			
			// 선택된 테마
			selectedTheme = "Theme_" + (position + 1);
			
			// 선택시 선택한 이미지로 변경하기
			// start coverflow
			BitmapDrawable drawable1 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_1);
		    BitmapDrawable drawable2 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_2);
		    BitmapDrawable drawable3 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_next);
		    BitmapDrawable drawable4 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_1_checked);
		    BitmapDrawable drawable5 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_2_checked);
		    BitmapDrawable drawable6 = (BitmapDrawable)getResources().getDrawable(R.drawable.theme_3_checked);
		    
		    BitmapDrawable[] images = {
		    		drawable1,
		    		drawable2,
		    		drawable3
		    };
		    
		    // 다른 패키지에서 리소스 참조하기
	        Context con1;
			try {
				con1 = createPackageContext("com.myjjun.pandaclocktheme1", 0);
				Resources res1 = con1.getResources(); 
		        int resid = res1.getIdentifier("theme_1", "drawable", "com.myjjun.pandaclocktheme1");
		        BitmapDrawable bd = (BitmapDrawable)res1.getDrawable(resid);
		        images[2] = bd;
		        downlaodedTheme[0] = true;	// 테마를 다운 받았음.
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    
		    // 선택한 테마 체크한 이미지로 변경
			if (position == 0) {
				images[0] = drawable4;
			} else if (position == 1) {
				images[1] = drawable5;
			} else if (position == 2 && downlaodedTheme[0] == true) {
				images[2] = drawable6;
			}
			
			ImageAdapter adapter = new ImageAdapter(PandaClockConfigure.this, images);
			adapter.createReflectedImages();
			
			GalleryFlow galleryFlow = (GalleryFlow) findViewById(R.id.Gallery01);
			galleryFlow.setAdapter(adapter);
			// end coverflow
		    
			// WebView 띄우기
			if (position == 2) {
				if (downlaodedTheme[0] == false) {
					startActivity(new Intent(PandaClockConfigure.this, WebViewActivity.class));
				}
			}
		}
	};
	
	/**
	 * Interface definition for a callback to be invoked when a view is clicked.
	 * OK 버튼 Click 이벤트
	 * 
	 * @see android.view.View.OnClickListener
	 * 
	 * @author junhwan_kim
	 * @date 2011. 4. 29. 오전 11:29:51
	 */
	Button.OnClickListener mClickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnOK:
				if(selectedTheme != null) {
					if (selectedTheme.equals(THEME_1) || selectedTheme.equals(THEME_2) || downlaodedTheme[0] == true) {
						/// widgetID별로 설정을 SharedPreference에 저장한다.
						String [] prefValue = {String.valueOf(mAppWidgetId), selectedTheme, "1", "1", "1"};
						
				    	PandaClockPreferences.setPref(getBaseContext(), prefValue);
				    	PandaClockPreferences.setWidgetId(getBaseContext(), String.valueOf(mAppWidgetId));
				    	
				    	/// 최초의 업데이트를 수행한다.
				    	AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getBaseContext());
				    	PandaClockProvider2x3.updateWidget(getBaseContext(), appWidgetManager, mAppWidgetId);
				    	
				    	/// Configure의 일반 종료 처리
				    	Intent intent = new Intent();
				    	intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
				    	setResult(RESULT_OK, intent);
				    	finish();
					} else {
						Toast.makeText(getBaseContext(), "활성화된 테마를 선택해주세요", Toast.LENGTH_SHORT).show();
					}
			    }
				break;
			case R.id.btnCancel:
				finish();
				break;
			}
		}
	};
	
	@Override
	protected void onDestroy() {
		RecycleUtils.recursiveRecycle(getWindow().getDecorView());
		System.gc();
		
		Log.i(TAG, "onDestoy()");
		
		super.onDestroy();
	}
}
